package cn.shengchao.dubbo.api.student;

import cn.shengchao.examstar.member.acl.ports.repostories.IStudentRepository;
import cn.shengchao.examstar.pay.acl.ports.repositories.IOrderRepository;
import cn.shengchao.examstar.rpc.base.PageResult;
import cn.shengchao.examstar.rpc.student.api.IStudentRpc;
import cn.shengchao.examstar.rpc.student.req.StudentQueryPage;
import cn.shengchao.examstar.rpc.student.res.StudentList;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.AsyncTaskExecutor;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.*;

/**
 * @program: examstarapi
 * @description: rpc
 * @author: Xiong weiqiang
 * @create: 2025-05-30 10:06
 */
@DubboService
public class StudentRpc implements IStudentRpc {

    @Autowired
    private IStudentRepository studentRepository;
    @Autowired
    private IOrderRepository orderRepository;
    @Autowired
    private AsyncTaskExecutor asyncTaskExecutor;
    @Override
    public PageResult<StudentList> getStudentList(StudentQueryPage studentQueryPage) {
        try (Page<StudentList> page = PageHelper.startPage(studentQueryPage.getPage(), studentQueryPage.getSize())) {
            List<StudentList> studentLists = studentRepository.getStudentList(studentQueryPage);
            //线程池，CompletableFuture有上下文。
            try (ExecutorService executorService = Executors.newFixedThreadPool(studentLists.size())){
                List<CompletableFuture<Void>> futures = studentLists.stream().map(
                        dto -> CompletableFuture.supplyAsync(
                                () ->  orderRepository.countUserPay(dto.getId()),
                                CompletableFuture.delayedExecutor(0, java.util.concurrent.TimeUnit.MILLISECONDS, executorService)
                        ).thenAccept(orderCountInfo -> {
                            dto.setOrdersSum((orderCountInfo==null||orderCountInfo.getOrdersSum()==null)?0L:orderCountInfo.getOrdersSum());
                            dto.setAmountOfConsumption((orderCountInfo==null||orderCountInfo.getOrderAmount()==null)? BigDecimal.ZERO:orderCountInfo.getOrderAmount());
                        })).toList();
                CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
            }
            return PageResult.of(page.getTotal(), studentLists);
        }
    }

    @Override
    public void changeStatus(Long studentId) {
        studentRepository.changeStatus(studentId);
    }
}